//
//  AIManager.m
//  AI
//
//  Created by 甘世清 on 2023/7/9.
//

#import "Manager.h"
#import "ViewController.h"
#import "LoginViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "InfoSetUpViewController.h"
#import <Accelerate/Accelerate.h>
@implementation Manager
+(UIViewController*)SQ_getViewController{
    UIViewController * vc ;
        if ([[UserModel share].token isNotEmpty]) {
            if (![[UserModel share].name isNotEmpty]||![[UserModel share].portrait isNotEmpty]) {
                vc =  [[InfoSetUpViewController alloc]init];
            } else {
                vc =  [[ViewController  alloc]init];
            }
        } else {
             //未登录
            vc = [[LoginViewController alloc]init];
        }
    return vc;
}

+ (UIViewController*)SQ_getCurrentViewController{
   ;
  UIViewController* vc = [UIApplication sharedApplication].windows.firstObject.rootViewController;
  while (1) {
    if ([vc isKindOfClass:[UITabBarController class]]) {
        vc = ((UITabBarController*)vc).selectedViewController;
    }
    if ([vc isKindOfClass:[UINavigationController class]]) {
        vc = ((UINavigationController*)vc).visibleViewController;
    }
    if (vc.presentedViewController) {
        vc = vc.presentedViewController;
    }else{
        break;
    }
   }
   return vc;
}

/// 根据key存储值
/// @param value 值
/// @param key key
+(void)SQ_SetObject:(NSString*)value FormKey:(NSString*)key
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    [user setObject:value forKey:key];
    [user synchronize];
}
/// 根据key删除值
/// @param key key
+(void)SQ_removeObjectForKey:(NSString*)key
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    [user removeObjectForKey:key];
    [user synchronize];
}
/// 根据key取值
/// @param key KEY
+(NSString*)SQ_stringForKey:(NSString*)key
{
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    return [user stringForKey:key];
}
/// 根据数据判断去对应的根视图
+(void)SQ_goToVC{
   UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc]init]];
        [Manager SQ_getCurrentViewController].view.window.rootViewController = nav;
}

/**
 *  获取上一个月的时间
 */
+ (NSString *)getLastMonth:(int)year
{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
        [lastMonthComps setYear:year]; // year = 1表示1年后的时间 year = -1为1年前的日期，month day 类推
//    [lastMonthComps setMonth:-1];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *dateStr = [formatter stringFromDate:newdate];
//    NSLog(@"date str = %@", dateStr);
    return dateStr;
}

/// 时间
/// @param time 时间戳
+(NSString * )SQ_getTimeString:(NSString*)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd"];
    NSDate *needFormatDate = [NSDate dateWithTimeIntervalSince1970:[time intValue]];
    NSDate *nowDate = [NSDate dateWithTimeIntervalSince1970:[[NSString SQ_currentTime] intValue]];
    int oldTime = [time intValue];
    int newTime = [[NSString SQ_currentTime] intValue];
    int result = newTime - oldTime;
    if (result < 60) { //秒
        return  SQNSLocalString(@"刚刚");
    }
    int miao = result/60; //分钟
    if ( miao <60 ) {
        return [NSString stringWithFormat:@"%d %@",miao,SQNSLocalString(@"分钟前")];
    }
    NSString * timeHours =  [NSString SQ_time:time Formatter:@"HH:mm"];
    int hours = miao/60; //小时
    if ( hours < 24 ) { //不超过24小时
        return timeHours;
    }
    if(result <= 60*60*24){   //// 在两天内的
        NSString * need_yMd = [dateFormatter stringFromDate:needFormatDate];
        NSString *now_yMd = [dateFormatter stringFromDate:nowDate];
        
        [dateFormatter setDateFormat:@"HH:mm"];
        if ([need_yMd isEqualToString:now_yMd]) {
            //// 在同一天
            return [NSString stringWithFormat:@"今天 %@",[dateFormatter stringFromDate:needFormatDate]];
        }else{
            ////  昨天
            return [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
        }
    }
    [dateFormatter setDateFormat:@"yyyy"];
    NSString * yearStr = [dateFormatter stringFromDate:needFormatDate];
    NSString *nowYear = [dateFormatter stringFromDate:nowDate];
    
    if ([yearStr isEqualToString:nowYear]) {
        ////  在同一年
        [dateFormatter setDateFormat:@"MM月dd日"];
        return [dateFormatter stringFromDate:needFormatDate];
    }else{
        [dateFormatter setDateFormat:@"yyyy/MM/dd"];
        return [dateFormatter stringFromDate:needFormatDate];
    }
}


+(NSString*)SQ_getStringID
{
    NSString * idstring = [Manager SQ_stringForKey:@"account"];
    if ([idstring isNotEmpty]) {
        return  idstring;
    }
//    return  @"1708617579_3703900F-6F24-490E-9CFE-EE82908E5EA5";
    NSString * ID = [NSString stringWithFormat:@"%@_%@",[NSString SQ_currentTime],[NSString aliyun_generateUUID]];
    return ID;
}
 

 
+ (CGSize)SQ_boundingAttributedStringRectWithSize:(CGSize)size
                                     lineSpace:(CGFloat)lineSpace
                                      textFont:(UIFont *)textFont
                                        string:(NSString *)string
{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.lineSpacing = lineSpace;
    NSDictionary *attribute = @{NSFontAttributeName:textFont,
                                NSParagraphStyleAttributeName:paraStyle};
    return [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
}


+(void)SQ_checkNotificationAuth:(void(^)(BOOL granted))block
{
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
                block(YES);
            }else {
                block(NO);
            }
        }];
}

+ (UIImage *)SQ_boxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur{
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 40);
    boxSize = boxSize - (boxSize % 2) + 1;
    CGImageRef img = image.CGImage;
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    void *pixelBuffer;
    //从CGImage中获取数据
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    //设置从CGImage获取对象的属性
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) *
                         CGImageGetHeight(img));
    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(
                                             outBuffer.data,
                                             outBuffer.width,
                                             outBuffer.height,
                                             8,
                                             outBuffer.rowBytes,
                                             colorSpace,
                                             kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    free(pixelBuffer);
    CFRelease(inBitmapData);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    return returnImage;
}

+(void)SQ_addAnimation:(UIView*)view{
    CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1)]];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.15, 1.15, 1)]];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.85, 0.85, 1)]];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1, 1.1, 1)]];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1)]];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.05, 1.05, 1)]];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.95, 0.95, 1)]];
    [array addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)]];
    animation1.values = array;
    animation1.duration = 2;
    animation1.repeatCount = MAXFLOAT;
    animation1.removedOnCompletion = NO;
    [animation1 setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    [view.layer addAnimation: animation1 forKey:@"myScale"];
}
 

@end
